<template>
  <div class="module_container">
    <div class="module_content">
      <div class="title">
        <span>模块管理</span>
      </div>
      <div class="function">
        <a-button @click="addData">添加</a-button>
        <!-- 添加事件弹出框 -->
        <a-modal
          cancelText="取消"
          okText="确定"
          title="添加模块"
          :visible="addVisible"
          @ok="addHandleOk"
          @cancel="addHandleCancel"
        >
          <div class="addContainer">
            <a-form-model
              :model="moduleForm"
              :rules="moduleFormRules"
              ref="moduleFormRef"
              :label-col="{ span: 4 }"
              :wrapper-col="{ span: 18 }"
            >
              <a-form-model-item prop="name" label="模块名称">
                <a-input v-model="moduleForm.name" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item label="按钮配图">
                <div>
                  <a-input
                    type="file"
                    class="inputUpload"
                    name="upload"
                    style="display: none"
                    accept="image/gif, image/jpeg, image/jpg, image/png, image/svg"
                    @change="uploadFile($event)"
                  ></a-input>

                  <div class="upload" @click="upload">
                    <a-icon
                      class="uploadIcon"
                      :type="loading ? 'loading' : 'plus'"
                    />
                    <!-- <a-icon class="uploadIcon" type="plus" /> -->
                  </div>
                  <span v-html="uploadedFileName">
                    <!-- 已上传文件小图标        没用(原因未知) -->
                    <!-- <a-icon type="paper-clip" /> -->
                    {{ uploadedFileName }}
                  </span>
                </div>
              </a-form-model-item>
              <a-form-model-item prop="exe" label="文件路径">
                <a-input v-model="moduleForm.exe" placeholder="请输入" />
              </a-form-model-item>
            </a-form-model>
          </div>
        </a-modal>
        <a-input
          v-model="searchText"
          @change="searchChange"
          placeholder="请输入关键字"
        >
          <a-icon slot="prefix" type="search" />
        </a-input>
      </div>
      <div class="table">
        <!-- 表头元素 -->
        <a-table
          :columns="columns"
          :data-source="data"
          rowKey="id"
          :customRow="clickRowTable"
          :pagination="{ pageSize: 9 }"
        >
          <span slot="name" slot-scope="text, record" v-html="record.name">{{
            record.name
          }}</span>
          <span slot="img_url" slot-scope="text, record">
            <a-tooltip placement="topLeft" title="点击放大">
              <div
                class="images"
                @click="enlarge"
                v-viewer.static="{ inline: false }"
              >
                <img
                  :src="record.img_url"
                  :key="record.img_url"
                  alt="按钮图片"
                />
              </div>
            </a-tooltip>
          </span>
          <span slot="exe" slot-scope="text, record" v-html="record.exe">{{
            record.exe
          }}</span>
          <span
            slot="currentTime"
            slot-scope="text, record"
            v-html="record.currentTime"
            >{{ record.currentTime }}</span
          >
          <span slot="handle" slot-scope="text, record, index">
            <a-tooltip placement="topLeft" title="查看详情">
              <img
                class="detailImg"
                @click="clickRow(record)"
                src="../../../assets/images/detail.png"
                alt="查看详情"
              />
            </a-tooltip>
            <a-tooltip placement="topLeft" title="编辑">
              <img
                @click="edit(record, index)"
                class="editImg"
                src="../../../assets/images/edit.png"
                alt="编辑"
              />
            </a-tooltip>
            <!-- 编辑事件弹出框 -->
            <a-modal
              title="修改模块"
              cancelText="取消"
              okText="确定"
              :visible="editVisible"
              @ok="editHandleOk"
              @cancel="editHandleCancel"
            >
              <div class="editContainer">
                <a-form-model
                  :model="moduleForm"
                  :rules="moduleFormRules"
                  ref="moduleFormRef"
                  :label-col="{ span: 4 }"
                  :wrapper-col="{ span: 18 }"
                >
                  <a-form-model-item prop="name" label="模块名称">
                    <a-input v-model="moduleForm.name" placeholder="请输入" />
                  </a-form-model-item>
                  <a-form-model-item prop="img_url" label="按钮配图">
                    <div>
                      <a-input
                        type="file"
                        class="inputUpload"
                        name="upload"
                        style="display: none"
                        accept="image/gif, image/jpeg, image/jpg, image/png, image/svg"
                        @change="uploadFile($event)"
                      ></a-input>
                      <div class="upload" @click="upload">
                        <a-icon class="uploadIcon" type="plus" />
                        <!-- <a-icon :type="loading ? 'loading' : 'plus'" /> -->
                      </div>
                      <span v-html="uploadedFileName">
                        <!-- 已上传文件小图标        没用(原因未知) -->
                        <!-- <a-icon type="paper-clip" /> -->
                        {{ uploadedFileName }}
                      </span>
                    </div>
                  </a-form-model-item>
                  <a-form-model-item prop="exe" label="文件路径">
                    <a-input v-model="moduleForm.exe" placeholder="请输入" />
                  </a-form-model-item>
                </a-form-model>
              </div>
            </a-modal>
            <a-tooltip placement="topLeft" title="删除">
              <img
                @click="del(record)"
                class="deleteImg"
                src="../../../assets/images/delete.png"
                alt="删除"
              />
            </a-tooltip>
            <!-- 删除事件弹出框 -->
            <a-modal
              title="确认删除"
              cancelText="取消"
              okText="确定"
              :visible="delVisible"
              @ok="delHandleOk"
              @cancel="delHandleCancel"
            >
              <p class="deleteText">
                <i class="iconfont icon-zhiwei-quanbuzhiwei"></i>
                确认删除{{ delName }}?
              </p>
            </a-modal>
          </span>
        </a-table>
      </div>
    </div>
  </div>
</template>
<script>
import {
  getAllModuleInfo,
  addModuleInfo,
  changeModuleInfo,
  delModuleInfo,
  uploadFiles
} from '../../../api/moduleInfo'
const columns = [
  {
    title: '模块名称',
    dataIndex: 'name',
    key: 'name',
    ellipsis: true
  },
  {
    title: '创建时间',
    dataIndex: 'currentTime',
    key: 'currentTime',
    ellipsis: true
  },
  {
    title: 'EXE文件路径',
    dataIndex: 'exe',
    key: 'exe',
    ellipsis: true
  },
  {
    title: '按钮配图',
    dataIndex: 'img_url',
    scopedSlots: { customRender: 'img_url' },
    ellipsis: true
  },
  {
    title: '操作',
    dataIndex: 'handle',
    align: 'left',
    scopedSlots: { customRender: 'handle' }
  }
]
export default {
  data() {
    return {
      data: [],
      columns,
      progress: 0,
      // switch: true,
      // viewer: null,

      // 上传图片
      uploadedFileName: '',
      fileData: {},
      // imageUrl: '',

      // 搜索
      searchText: '',
      searchData: [],

      // 删除
      delId: '',
      delName: '',
      delVisible: false,
      delFounderId: '',

      // 编辑
      editVisible: false,
      editIndex: 0,
      moduleForm: {
        name: '',
        exe: '',
        img_url: '',
        img_id: '5f6c6a4dc2fa9644acb55c8d',
        operator_id: '',
        founder_id: ''
      },
      moduleFormRules: {
        exe: [{ required: true, message: '用户名不能为空', tigger: 'blur' }],
        name: [{ required: true, message: '类型不能为空', tigger: 'blur' }]
      },

      // 添加
      loading: false,
      addVisible: false
    }
  },
  mounted() {
    this.getModule()
  },
  methods: {
    // 表格每行的点击事件 查看详情
    clickRowTable(record) {
      const vm = this
      return {
        on: {
          click: () => {
            // 点击该行时要做的事情
            vm.clickRow(record)
          }
        }
      }
      // 事件
    },
    clickRow(record) {
      const vm = this
      const currentKey = '5'
      sessionStorage.setItem('currentKey', JSON.stringify(currentKey))
      const moduleSession = {}
      moduleSession.id = record.id
      moduleSession.name = record.name
      sessionStorage.setItem('moduleId', JSON.stringify(moduleSession))
      vm.$router.push({
        path: '/Index/module/detail'
      })
      event.stopPropagation() // 阻止事件冒泡
    },
    // 图片点击放大
    enlarge() {
      event.stopPropagation() // 阻止事件冒泡
    },
    // 获取所有模块信息
    getModule() {
      const vm = this
      getAllModuleInfo().then((res) => {
        console.log('模块信息', res)
        if (res.code === 200) {
          res.data.map((item) => {
            item.img_url = 'data:image/png;base64,' + item.img_url
          })
          vm.data = res.data
          vm.data.map((item) => {
            vm.getCTime(item)
            item.id = item._id
          })
          vm.searchData = JSON.parse(JSON.stringify(vm.data))
        }
      })
    },
    // 表格的添加事件

    // 上传图片
    upload() {
      const inputUpload = document.querySelector('.inputUpload')
      inputUpload.click()
    },
    uploadFile(event) {
      const vm = this
      if (vm.uploadedFileName.includes('请添加按钮配图')) {
        vm.uploadedFileName = ''
      } else {
      }
      vm.uploadedFileName = event.target.files[0].name
      console.log(event.target.files[0].name)
      // 上传图片或文件获取图片或文件id
      // 文件上传
      const formData = new FormData()
      formData.append('file', event.target.files[0])
      vm.fileData = formData
    },
    // 表格的添加事件

    addData() {
      this.fileData = {}
      this.uploadedFileName = ''
      this.moduleForm.name = ''
      this.moduleForm.exe = ''
      this.moduleForm.img_url = ''
      this.addVisible = true
    },
    addHandleCancel() {
      this.addVisible = false
    },
    addHandleOk() {
      const vm = this
      vm.$refs.moduleFormRef.validate((valid) => {
        if (!valid) return
        if (vm.uploadedFileName === '') {
          vm.uploadedFileName = '<span style="color: red">请添加按钮配图</span>'
        } else {
          // 页面伪添加操作
          // 获取创建人
          const userId = JSON.parse(sessionStorage.getItem('data')).data.user_id
          vm.moduleForm.founder_id = userId
          console.log('111111111111111111111111')
          // var config = {
          //   onUploadProgress: (e) => {
          //     var progressPercent = (e.loaded / e.total) * 100
          //     vm.progress = progressPercent
          //   }
          // }
          // 异步添加操作
          uploadFiles(1, vm.fileData).then((res) => {
            console.log('13333333333333333333333333')
            // 上传图片或文件的异步请求
            if (res.code === 200) {
              vm.moduleForm.img_id = res.data._id
              addModuleInfo(vm.moduleForm).then((res) => {
                if (res.code === 200) {
                  this.getModule()
                  this.searchChange()
                  vm.$message.success('添加成功')
                }
              })
            }
          })
          // setInterval(function () {
          //   console.log('vm.progress', vm.progress)
          // }, 1000)
          this.addVisible = false
        }
      })
    },
    // 表格的编辑事件
    edit(record, index) {
      this.fileData = {}
      this.uploadedFileName = ''
      this.editVisible = true
      this.editIndex = index
      this.moduleForm = JSON.parse(JSON.stringify(record))
      event.stopPropagation() // 阻止事件冒泡
    },
    editHandleOk() {
      const vm = this
      vm.$refs.moduleFormRef.validate((valid) => {
        if (!valid) return
        // 获取创建人
        vm.moduleForm.operator_id = JSON.parse(
          sessionStorage.getItem('data')
        ).data.user_id
        if (vm.moduleForm.operator_id !== vm.moduleForm.founder_id) {
          vm.$message.error('操作失败!您没有权限进行此项操作!')
        } else {
          changeModuleInfo(vm.moduleForm.id, vm.moduleForm).then((res) => {
            if (res.code === 200) {
              this.getModule()
              this.searchChange()
              vm.$message.success('修改成功')
            }
          })
        }
        vm.editVisible = false
      })
    },
    editHandleCancel() {
      // this.switch = true
      this.editVisible = false
    },
    // 表格的删除事件
    del(record) {
      // this.switch = false
      this.delFounderId = record.founder_id
      this.delId = record.id
      this.delName = record.name
      this.delVisible = true
      event.stopPropagation() // 阻止事件冒泡
    },
    delHandleOk() {
      const vm = this
      // vm.switch = true
      const operatorId = JSON.parse(sessionStorage.getItem('data')).data.user_id
      if (operatorId !== vm.delFounderId) {
        vm.$message.error('操作失败!您没有权限进行此项操作!')
      } else {
        // const data = vm.data.filter((item) => item.id !== vm.delId)
        // vm.data = data
        const tmpData = {}
        tmpData.operator_id = operatorId
        delModuleInfo(vm.delId, tmpData).then((res) => {
          if (res.code === 200) {
            vm.getModule()
            vm.searchChange()
            vm.$message.success('删除成功')
          }
        })
        vm.delVisible = false
      }
    },
    delHandleCancel() {
      // this.switch = true
      this.delVisible = false
    },
    // 处理时间戳
    getCTime(item) {
      const time = new Date(item.ctime * 1000)
      const y = time.getFullYear()
      const m = time.getMonth() + 1
      const d = time.getDate()
      const h = time.getHours()
      const mm = time.getMinutes()
      const s = time.getSeconds()
      item.currentTime =
        y +
        '-' +
        this.add0(m) +
        '-' +
        this.add0(d) +
        ' ' +
        this.add0(h) +
        ':' +
        this.add0(mm) +
        ':' +
        this.add0(s)
    },
    add0(m) {
      return m < 10 ? '0' + m : m
    },

    // 搜索
    // 搜索框输入内容变化时触发
    searchChange() {
      const vm = this
      let value = this.searchText
      value = value.trim()
      const tmpData = JSON.parse(JSON.stringify(vm.searchData))
      vm.data = tmpData.filter(
        (item) =>
          String(item.name).includes(value) ||
          String(item.exe).includes(value) ||
          String(item.currentTime).includes(value)
      )
      // 字符串替换,含搜索词汇的字符串高亮
      // const replaceReg = new RegExp(value, 'i')
      // const replaceString = '<span style="color: red">' + value + '</span>'
      // const arr = vm.data
      // for (let i = 0; i < arr.length; i++) {
      //   arr[i].name = String(arr[i].name).replace(replaceReg, replaceString)
      //   arr[i].category = String(arr[i].category).replace(
      //     replaceReg,
      //     replaceString
      //   )
      //   arr[i].power = String(arr[i].power).replace(replaceReg, replaceString)
      //   arr[i].founder = String(arr[i].founder).replace(
      //     replaceReg,
      //     replaceString
      //   )
      //   arr[i].currentTime = String(arr[i].currentTime).replace(replaceReg, replaceString)
      //   arr[i].type = String(arr[i].type).replace(replaceReg, replaceString)
      // }
      // vm.data = arr
      console.log(' vm.searchData', vm.data)
    }
  }
}
</script>
<style>
.module_container {
  height: 100%;
  width: 100%;
  padding: 31px 32px;
  /* background-color: blue; */
  background-color: rgba(246, 246, 250);
}
.module_container .module_content {
  height: 100%;
  width: 100%;
  padding-top: 24px;
  background-color: #fff;
  z-index: 7;
  box-shadow: 0px 10px 21px rgba(3, 57, 165, 0.08);
}
/* 标题 最左上角的 */
.module_content .title {
  margin-left: 36px;
  font: bold 20px 'PingFang SC';
}
/* 第二行的按钮和搜索框 */
.module_content .function {
  display: flex;
  justify-content: space-between;
  margin-top: 24px;
  padding: 0 36px;
}
/* 第二行按钮 */
.module_content .function .ant-btn {
  height: 35px;
  width: 100px;
  color: #ffffff;
  font: bold 16px 'PingFang SC';
  background-color: #2c5bb9;
  border-color: #2c5bb9;
  box-shadow: 0px 7px 14px rgba(44, 91, 185, 0.47);
}
/* 第二行输入框 */
.function .ant-input-affix-wrapper .ant-input {
  border: 1px solid #2c5bb9;
}
.function .ant-input-prefix .anticon {
  font-size: 18px;
  color: #8f97a8;
}
.ant-input-affix-wrapper .ant-input-prefix {
  left: 6px;
}
.module_content .function .ant-input-affix-wrapper {
  height: 35px;
  width: 293px;
}
/* 表格 */
.module_content .table {
  margin-top: 25px;
}

/* 表格图片大小 */
.module_content .table .images {
  cursor: pointer;
  height: 40px;
  width: 40px;
}
.module_content .ant-table-tbody tr td:nth-child(4) {
  padding: 0px 0px 0px 16px;
}
/* .module_content .table .images {
  position: absolute;
  margin: ;
  height: 50px;
  width: 50px;
} */
.module_content .table .images img {
  /* line-height: 50px; */
  height: 100%;
  width: 100%;
}

/* 查看详情 */
.module_content .ant-table-body .ant-table-tbody .ant-table-row .detail {
  color: #4395ff;
  cursor: pointer;
  padding: 0;
}
/* 分页页数样式 */
.module_content .ant-pagination-item a,
.module_content .ant-pagination-disabled a {
  color: #8f97a8;
}
.module_content .ant-pagination-next .ant-pagination-item-link:hover,
.module_content .ant-pagination-prev .ant-pagination-item-link:hover {
  border-color: #4c72bd;
  color: #4c72bd;
}
.module_content .ant-pagination-item,
.module_content .ant-pagination-prev .ant-pagination-item-link,
.module_content .ant-pagination-next .ant-pagination-item-link {
  border-color: #8f97a8;
}
.module_content .ant-pagination .ant-pagination-item-active a {
  color: #fff;
}
.module_content .ant-pagination .ant-pagination-item-active {
  background-color: #4c72bd;
  border-color: #4c72bd;
}
/* 表格行hover */
.module_content .ant-table-body .ant-table-tbody .ant-table-row {
  width: 1600px;
  position: relative;
}
.module_content .ant-table-body .ant-table-tbody .ant-table-row:hover::after {
  z-index: 9;
  content: '';
  position: absolute;
  left: 50%;
  transform: translate(-50%, -100%);
  height: 60px;
  width: 101%;
  box-shadow: 0px 4px 25px rgba(46, 94, 190, 0.6);
  border: 10px solid #4f7bd1;
  border-radius: 8px;
}
.module_content .ant-table-body .ant-table-tbody .ant-table-row:hover .detail {
  background-color: #4f7bd1;
  transition-duration: 0s;
}
.module_content .ant-table-body .ant-table-tbody .ant-table-row:hover td {
  position: relative;
  z-index: 99;
  transition-duration: 0s;
  border-bottom: none;
  color: #fff;
  background-color: #4f7bd1;
}
/* 操作删除编辑按钮 */
.module_content .table .deleteImg {
  margin-left: 25px;
  height: 22px;
  width: 17px;
  cursor: pointer;
}
.module_content .table .detailImg {
  width: 20px;
  height: 22px;
  cursor: pointer;
}
.module_content .table .editImg {
  margin-left: 25px;
  height: 23px;
  width: 23px;
  cursor: pointer;
}
.deleteText {
  font-size: 16px;
}
.icon-zhiwei-quanbuzhiwei {
  font-size: 16px;
  color: #0339a5;
}
.ant-modal-title {
  color: #fff;
}
/* 弹出框表头 修改默认组件需要全局样式才能完成修改 */
.ant-modal-header {
  background-color: #0339a5;
}
.ant-modal-footer .ant-btn {
  border: 1px solid #2c5bb9;
}
.ant-modal-footer .ant-btn-primary {
  background-color: #2c5bb9;
}
.ant-table-tbody tr td:first-child {
  padding-left: 35px;
}
.ant-table-thead tr th:first-child {
  padding-left: 35px;
}
.ant-table-tbody tr td:last-child {
  display: flex;
  padding: 16px 0px 16.5px 16px;
}
/* 表头颜色*/
.ant-table-column-title {
  font: bold 18px 'PingFang SC';
  color: #142c5c;
}
.ant-table {
  font-size: 16px;
  color: #575c66;
}
.ant-table-content .ant-table-body .ant-table-thead > tr > th {
  background-color: rgba(229, 235, 247, 1);
}
/* 添加按钮图片 */
.upload:hover {
  border: 1px dashed rgb(64, 169, 255);
}
.upload {
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  height: 66px;
  width: 66px;
  border: 1px dashed #ccc;
}
.upload .uploadIcon {
  display: inline-block;
  font-size: 25px;
}

.ant-form-item-required::before {
  display: none;
}
</style>
